package model.User.controller;



import model.User.entity.Result;
import model.User.entity.StatusCode;
import model.User.entity.User;
import model.User.service.IUserService;

import model.User.util.SMSCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;



/**
 * Created by Sunshine、宸 on 2019/6/25.
 */
@SuppressWarnings("all")
@RestController
public class UserController {
    @Autowired
    private IUserService iUserService;

    //根据id查找所有信息
    @CrossOrigin
    @GetMapping("/user/{informationId}")
    public Result user(@PathVariable("informationId") Integer informationId){

        User user=iUserService.findById(informationId);
        Result result=new Result(true, StatusCode.OK,"查询成功",user);
        System.out.println(result);
        return result;
    }

    @PostMapping("/password")
    @CrossOrigin
    public Result u(User user){
        Result result=null;
        //前端数据
        String password=user.getUserPassword();
        System.out.println(password);
        String confirmPassword=user.getUserConfirmpwd();
        System.out.println(confirmPassword);
        String email=user.getUserEmail();
        String phone=user.getUserPhone();

        //如果前端密码和确认密码相同且不为空
        if(password.equals(confirmPassword)&&password!=null&&confirmPassword!=null){
            User user1=iUserService.findByEmail(user);
            user1.setUserPassword(password);
            user1.setUserConfirmpwd(confirmPassword);
             iUserService.updateByUser(user1);
             result=new Result(true,StatusCode.OK,"密码修改成功！");
        }else {
            result=new Result(true,StatusCode.ERROR,"密码修改失败！");
        }
        return result;
    }

    /**
     * 根据手机号或者邮箱获取验证码
     * @param user
     * @param req
     * @return
     */
    @GetMapping("/code")
    @CrossOrigin
    public Result user(User user,HttpServletRequest req){
        Result result=null;
        //前端
       String email=user.getUserEmail();
       String phone=user.getUserPhone();

       //后端
        User user1=iUserService.findByEmail(user);
        String ema=user1.getUserEmail();
        String ph=user1.getUserPhone();


        if(user!=null){
            if(phone!=null) {
                if (phone.equals(ph)) {
//                    System.out.println(phone+"---------------");
                    user1.setUserFreeone(null);
                    iUserService.updateByUser(user1);
                    //随机产生6位数验证码
                    String code = RandomStringUtils.randomNumeric(6);
                    //把验证码放到session作用域中
//                    req.getSession().setAttribute("code", code);
                    user1.setUserFreeone(code);
                    iUserService.updateByUser(user1);
                    //发送验证码到手机
                    try {
                        SMSCode.sendCode(ph,code);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if(email!=null) {
                if (email.equals(ema)) {
//                    System.out.println(email+"++++++++++++++++++++");
                    user1.setUserFreeone(null);
                    iUserService.updateByUser(user1);
                    //随机产生6位数验证码
                    String code = RandomStringUtils.randomNumeric(6);
                    //把验证码放到session作用域中
//                    req.getSession().setAttribute("code", code);
                    user1.setUserFreeone(code);
                    iUserService.updateByUser(user1);

                    HtmlEmail el = new HtmlEmail();//创建一个HtmlEmail实例对象
                    el.setHostName("smtp.qq.com");
                    el.setCharset("utf-8");
                    el.setAuthentication(email, "mvigjkrkouubhbcf");//设置发送人到的邮箱和用户名和授权码(授权码是自己设置的)
                    try {
                        el.addTo(email);//设置收件人
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                    try {
                        el.setFrom("1142351748@qq.com", "lcy");//发送人的邮箱为自己的，用户名可以随便填
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }

                    el.setSubject("欢迎使用,您的验证码为：");//设置发送主题
                    try {
                        el.setMsg(code);//设置发送内容
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                    try {
                        el.send();
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                } else {
                    result = new Result(false, StatusCode.ERROR, "邮箱不存在！", user1);
                }

            }else{
                result = new Result(false, StatusCode.ERROR, "邮箱为空！",user1);
            }
        }else {
            result = new Result(false, StatusCode.ERROR, "邮箱或手机为空！",user1);
        }
        return result;
    }

    /**
     * 找回密码
     * @param u
     * @return
     */
    @GetMapping("/c")
    @CrossOrigin
    public Result use(User u) {
//        System.out.println(u);
        Result result=null;
        //获取前端
        String email=u.getUserEmail();
        String phone=u.getUserPhone();
        String freeOne=u.getUserFreeone();

        //数据库


        String pattern1 =  "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        //手机
        String REGEX_MOBILE = "(134[0-8]\\d{7})" + "|(" + "((13([0-3]|[5-9]))" + "|149" + "|15([0-3]|[5-9])" + "|166" + "|17(3|[5-8])" + "|18[0-9]" + "|19[8-9]" + ")" + "\\d{8}" + ")";



        //如果前端传过来的数据不为null
        if(u!=null){
            if(phone!=null){
                if(phone.matches(REGEX_MOBILE)){

                    User user=iUserService.findByEmail(u);
                    String ph=user.getUserPhone();
                    String em=user.getUserEmail();
                    String freeCode= user.getUserFreeone();
                    System.out.println(freeCode);

                    if(phone.equals(ph)&&freeOne.equals(freeCode)){

                        result=new Result(true, StatusCode.OK,"验证码正确！",user);
                        user.setUserFreeone(null);
                        iUserService.updateByUser(user);
                    }else{
                        result = new Result(false,StatusCode.LOGINERROR,"重置失败,验证码错误!");
                    }
                }else {
                    result = new Result(false, StatusCode.ErrorPhone, "重置失败,手机号不存在!");
                }
            }else if(email.matches(pattern1)){

                User user=iUserService.findByEmail(u);
                String ph=user.getUserPhone();
                String em=user.getUserEmail();
                String freeCode= user.getUserFreeone();
//                System.out.println(freeCode);

                    if(email.equals(em)&&freeOne.equals(freeCode)){

                        result=new Result(true, StatusCode.OK,"成功！",user);
                        user.setUserFreeone(null);
                        iUserService.updateByUser(user);

                    }else{
                        result = new Result(false,StatusCode.LOGINERROR,"重置失败,验证码错误!");
                    }
                }else {
                    result = new Result(false, StatusCode.EmailError, "登录失败,邮箱不存在!");
                }

        }else {
            result = new Result(false, StatusCode.ERROR, "登录失败,手机号或邮箱为空!");
        }
        return result;
    }

    /**
     * 注册要判断邮箱 电话   是否存在  如果存在提示邮箱或者电话已经存在
     * @param u
     * @param request
     * @return
     */

    @PostMapping("/reg")
    @CrossOrigin
    public Result result(User user){
        Result result=null;
        //获取前端
        String username=user.getUserName();
        String email=user.getUserEmail();
        String phone=user.getUserPhone();
        String password=user.getUserPassword();
        String confirmPwd=user.getUserConfirmpwd();

        System.out.println(user);
        //后端
        User u =iUserService.findByEmail(user);

        //判断u是否为空
        if("".equals(u)) {
            //如果u为空 说明没有此用户 可以进行保存
            if(username!=null&&email!=null&&phone!=null&&password!=null&&confirmPwd!=null){
                iUserService.Save(user);
                result=new Result(true,StatusCode.OK,"注册成功！",user);
            }else {
                result=new Result(false,StatusCode.ERROR,"请完善所有信息！",user);
            }

        }else if(null!=u){
            String em=u.getUserEmail();
            String ph=u.getUserPhone();
            if(phone.equals(ph)&&!email.equals(em)){
                result=new Result(false,StatusCode.ERROR,"手机号已经存在！");
            }else if(!phone.equals(ph)&&email.equals(em)){
                result=new Result(false,StatusCode.ERROR,"邮箱已经存在！");
            }else {
                result=new Result(false,StatusCode.ERROR,"邮箱和手机号已经存在！");
            }
        }



        return result;
    }


    /**
     * 登陆
     * @param u
     * @param request
     * @return
     */

    @PostMapping("/user")
    @CrossOrigin
    public Result result(User u,HttpServletRequest request){

        //u是前端传过来的数据
        String phone=u.getUserPhone();
        String email=u.getUserEmail();
        String password=u.getUserPassword();

        //数据库
        User user=iUserService.findByEmail(u);
        String ph=user.getUserPhone();
        String em=user.getUserEmail();
        String pwd=user.getUserPassword();
        //邮箱
        String pattern1 =  "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        //手机
        String REGEX_MOBILE = "(134[0-8]\\d{7})" + "|(" + "((13([0-3]|[5-9]))" + "|149" + "|15([0-3]|[5-9])" + "|166" + "|17(3|[5-8])" + "|18[0-9]" + "|19[8-9]" + ")" + "\\d{8}" + ")";

        Result result=null;

       //如果前端传过来的数据不为null
        if(u!=null){
            if(phone!=null){
                if(phone.matches(REGEX_MOBILE)){
                    if(phone.equals(ph)&&password.equals(pwd)){
                        request.getSession().setAttribute("u",u);
                        result=new Result(true, StatusCode.OK,"用户登录成功！");
                    }else{
                        result = new Result(false,StatusCode.LOGINERROR,"登录失败,密码错误!");
                    }
                }else {
                    result = new Result(false, StatusCode.ErrorPhone, "登录失败,手机号不存在!");
                }
            }else {
                if(email.matches(pattern1)){
                    if(email.equals(em)&&password.equals(pwd)){
                        request.getSession().setAttribute("u",u);
                        result=new Result(true, StatusCode.OK,"用户登录成功！");
                    }else{
                        result = new Result(false,StatusCode.LOGINERROR,"登录失败,密码错误!");
                    }
                }else {
                    result = new Result(false, StatusCode.EmailError, "登录失败,邮箱不存在!");
                }
            }
        }else {
            result = new Result(false, StatusCode.ERROR, "登录失败,手机号或邮箱为空!");
        }

        return result;
    }

}
